#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>        // close()
#include <arpa/inet.h>     // inet_pton()
#include <sys/socket.h>
#include <netinet/in.h>

#define SERVER_PORT 8080
#define BUFFER_SIZE 1024
#define SERVER_IP "127.0.0.1"    // 本地服务器

int main(){
    //1. 创建socket
    int client_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if(client_fd < 0){
        perror("socket");
        exit(1);
    }

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(SERVER_PORT);
    inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr);
 
    //2. 发送和接受
    while(1){
        printf("please intput: \n");
        char buffer[BUFFER_SIZE]={0};
        fgets(buffer, BUFFER_SIZE-1, stdin);

        if(strncmp(buffer,"quit",4)==0){
            break;
        }

        int send_len = sendto(client_fd, buffer, strlen(buffer),0,
        (struct sockaddr*)(&server_addr),sizeof(server_addr));
        if(send_len < 0){
            perror("sendto");
            exit(1);
        }

        memset(buffer,0, BUFFER_SIZE);
        int server_len = sizeof(server_addr);
        int recv_len = recvfrom(client_fd, buffer, BUFFER_SIZE-1,0,(struct sockaddr *)&server_addr,
        &server_len);

        //recvfrom(client_fd, buffer, BUFFER_SIZE-1, 0, NULL, NULL);
        if(recv_len < 0){
            perror("recvfrom");
            exit(1);
        }
        printf("receive server msg : %s\n", buffer);
    }

    close(client_fd);
}